import {
	SER_USERINFOR
} from '@/store/mutation-types.js';
// 获取配置文件
import config from '@/static/js/config.js';
// vuex
import {
	mapGetters,
	mapMutations,
	mapActions,
	mapState
} from 'vuex';
// 请求
import {
	createOrderNewAPI,
	agOrderPayAPI,
} from '@/request/restaurant/index.js';
const restaurantmixins = {
	data() {
		return {
			shopid: 0,
			countDown: 0,
			wait_for: '',
			SER_USERINFOR,
			// 0:待支付;1:待出餐(WAIT_OUT_MEAL);2:已出餐(OUT_MEAL);3:订单失败(FAIL);4:已出餐（部分退款）(OUT_MEAL_PART);5:取消
			OrderStatus0: 0,
			OrderStatus1: 1,
			OrderStatus2: 2,
			OrderStatus3: 3,
			OrderStatus4: 4,
			OrderStatus5: 5,
		}
	},
	filters: {
		// 订单状态
		OrderState(v) {
			switch (v) {
				case 0:
					return '待支付';
				case 1:
					return '待出餐';
				case 2:
					return '已出餐';
				case 3:
					return '已退款';
				case 4:
					return '已出餐（部分退款）';
				case 5:
					return '已关闭';
			}
		},

		// 订单状态对应文字
		OrderStateText(v) {
			switch (v) {
				case 0:
					return '待支付';
				case 1:
					return '实付';
				case 2:
					return '实付';
				case 3:
					return '实付';
				case 4:
					return '实付';
				case 5:
					return '待支付';
			}
		}
	},
	computed: {
		BrandStyle() {},
		...mapState({
			cartList: 'shopping/cartList'
		}),
		...mapGetters({
			// 获取用户自主改变的地址
			UserArae1: 'GetUserArae',
			// 获取用户设备定位的地址
			GetcityInfor: 'GetcityInfor',
			// 获取用户设备定位的地址
			UserArae2: 'GetcityInfor',
			// 获取用户切换的城市code
			GetCityCode: 'GetCityCode',
			// 获取品牌Id
			BrandInfor: 'shopping/BrandInfor',
			// 获取店铺信息
			GetShopInfor: 'shopping/GetShopInfor',
			// 获取导航索引
			Getnavindex: 'shopping/Getnavindex',
			// 获取购物车
			GetCartList: 'shopping/GetCartList',
			// 获取购物车
			GetCartList2: 'shopping/Getshopshopping',
			// 获取就餐方式
			GetMODE: 'shopping/GetMODE',
			getPhone: 'shopping/getPhone',
		}),
	},
	methods: {
		...mapMutations({
			SetcommodityInfor: 'shopping/SETINFOR',
			// 设置底部导航索引
			SETNAVINDEX: 'shopping/SETNAVINDEX',
			// 选择餐厅时保存餐厅信息
			SETSHOPDETAIL: 'shopping/SETSHOPDETAIL',
			// 肯德基首次进入存入弹框变量
			MODEAL: 'shopping/MODEAL',
			// 结算清单
			SETREPLACE: 'shopping/SETREPLACE',
			// 设置品牌信息
			SETBRANDINFOR: 'shopping/SETBRANDINFOR',
			// 获取本地购物车数据
			INIT_BUYCART: 'shopping/INIT_BUYCART',
			// 设置就餐方式
			SETMODE: 'shopping/SETMODE',
			// 设置手机号
			SETPHONE:'shopping/SETPHONE'
		}),
		...mapActions({
			// 清空当前购物车
			EMPTY: 'shopping/EMPTY',
			// 商品加入购物车
			ADD_CART: 'shopping/ADD_CART',
			// 移除商品
			REDUCE_CART: 'shopping/REDUCE_CART',
		}),
		Brand() {
			return config[`Brand_${this['BrandInfor']['brand_id']}`]
		},
		// 主题色方法
		// themeColor(){
		// 	// 肯德基主题色
		// 	if(BrandInfor['brand_id'] == 1){

		// 	}
		// }
		// 待支付倒计时
		/**
		 * @param {Number} status 订单的状态
		 * @param {Number} createtime 下单时间
		 */
		tiem(status, createtime, order_sn) {
			if (status !== 0) return;
			// 获取15分钟之后的时间
			let date = new Date(createtime * 1000);
			date.setMinutes(date.getMinutes() + 15);
			this['countDown'] = setTimeout(() => {
				// 最终停止时间时间戳
				let end = date.getTime();
				// 当前时间时间戳
				let start = new Date().getTime();
				let x = new Date(end - start);
				console.log(end - start, '执行2', order_sn);
				if ((end - start) <= 0) {
					try {
						this['InforData']['status'] = 5;
					} catch (e) {
						//TODO handle the exception
					}
					return;
				};
				this.tiem(status, createtime, order_sn)
				let m = x.getMinutes();
				m = m > 9 ? m : `0${m}`;
				let s = x.getSeconds();
				s = s > 9 ? s : `0${s}`;
				this['wait_for'] = `${m}:${s}`;
			}, 1000)
		},

		// 打开微信内置地图导航
		openLocation(latitude = (+this['GetShopInfor']['latitude']), longitude = (+this['GetShopInfor'][
			'longitude'
		])) {
			console.log(latitude, longitude);
			uni.openLocation({
				latitude,
				longitude,
				success: function() {
					console.log('success');
				}
			});
		},
		/**
		 * @瑞幸筛选出当前选择的高亮规格
		 * */
		screensku_rx() {
			let r = [];
			let t = this['skuinfor']['details']['specifications'];
			for (let i = 0; i < t['length']; i++) {
				let item = t[i];
				r.push(...item['ingredients']);
			};
			let newarr = r.filter(item => item['checked']).map(item => item['name']);
			return {
				sku: newarr,
				text: newarr.join('/')
			}
		},
		/**
		 * @星巴克筛选出当前选择的高亮规格
		 * @param { Array } optional规格数组
		 * @param { Number } pay_price原价
		 * */
		screensku_xbk(optional = this['skuinfor']['details']['optional'], pay_price = this['skuinfor'][
			'pay_price'
		]) {
			let add_price = 0;
			let r = [];
			let sku_code = [];
			// JSON.parse与JSON.stringify方法深拷贝，将双向数据解除
			// RetainDecimalPoint方法转为正常价格（后台返回的是按照 分 划分的）
			// let pay = +this.RetainDecimalPoint(JSON.parse(JSON.stringify(this['skuinfor']['pay_price'])));
			let pay = +JSON.parse(JSON.stringify(pay_price));
			// let t = this['skuinfor']['details']['optional'];
			let t = optional;
			for (let i = 0; i < t['length']; i++) {
				let item = t[i];
				r.push(...item['sku_infos']);
			};
			let newarr = r.filter(item => {
				if (item['checked']) {
					if (item?.price) {
						add_price = item['price'] * 100;
						// 商品的原价与配料价格相加
						pay += add_price
					};
					return item;
				}
			}).map(item => item['name']);
			// 数组格式
			// sku_code = t.map(item=>{
			// 	return {
			// 		specification_id:item['id'],
			// 		sku_id:item['sku_infos'].find(it=>{
			// 			return it['checked'];
			// 		})['id']
			// 	}
			// });

			// 字符串格式
			// let str = []; {
			// 	for (let i = 0; i < t['length']; i++) {
			// 		str.push(`${t[i]['id']}_${t[i]['sku_infos'].find(item=>item['checked'])['id']}`)
			// 	};
			// }
			// this['skuinfor']['sku_code'] = str.join(',');
			// this['skuinfor']['sku'] = newarr;
			// this['skuinfor']['pay'] = pay;
			// console.log(pay, '方法pay');
			return {
				// sku_code: str.join(','),
				sku: newarr,
				pay,
				add_price
			}
		},

		// 因为点餐模块中的底部导航是自定义的所以需要从内多层页面跳转到订单或者首页时使用这个方法
		/**
		 * @param {Number}  delta 回退页数
		 * @param {Boolean}  istab 是否设置导航
		 * @param {Number}  index 导航所以为几
		 */
		navigateBack(delta, istab = false, index = 0) {
			if (istab) {
				this.SETNAVINDEX(index)
			}
			uni.navigateBack({
				delta
			});
		},


		// 订单立即支付
		againpayment(order_sn,money = 0) {
			console.log(this['BrandInfor']['brand_id'], '品牌ID');
			let redirect_url;
			// 肯德基
			if (this['BrandInfor']['brand_id'] == 1 || this['BrandInfor']['brand_id'] == 5) {
				redirect_url = `/pages/restaurant/order/order-status/order-status`;
			}else{
				redirect_url = `/pages/restaurant/order/order-details/details`
			}
			// 小程序再次支付
			// 微信跳转H5后的逻辑为必须携带token
			const isWechat = getApp()['globalData']['parameters']?.isWechat;
			if(isWechat){
				this.payment({
					order_sn,
					type:3,
					redirect_url,
					money,
				});
			}else{
				// H5再次支付
				agOrderPayAPI({
					order_sn,
					type: 3,
					redirect_url: `${getApp()['globalData']['urlfileName']}/pages/pay/index?order_sn=${order_sn}&type=${3}&redirect_url=${redirect_url}`
				}).then(data => {
					location.href = data['data']['redirect_url'];
				})
			}
		},

		// 重新下单
		Reorder(commodity) {
			console.log(commodity, '重新下单商品');
			uni.showLoading({
				title: '加载中...',
			})
			let self = this;
			let index = 0;
			// 创建进入餐厅所需要的参数对象
			let {
				restaurant_id,
				latitude,
				longitude,
				restaurant_address,
				restaurant_name
			} = commodity[0];
			// 进入餐厅时设置的参数
			this.SETSHOPDETAIL({
				city_name: "",
				close_time: "",
				distance: "",
				open_time: "",
				province_name: "",
				regoin_name: "",
				special: false,
				latitude,
				longitude,
				restaurant_address,
				restaurant_id,
				restaurant_name,
			});
			let add = function() {
				console.log(`第${index}个,总共有${commodity['length']}`);
				console.log(commodity[index]['sku_code'],'sku_code');
				self.ADD_CART({
					commodity: commodity[index],
					quantity:commodity[index]['num']
				}).then(() => {
					if (index >= commodity['length'] - 1) {
						uni.hideLoading();
						uni.navigateTo({
							url: `/pages/restaurant/home/shop_home/shop_home?restaurant_id=${restaurant_id}`
						});
						return;
					};
					index += 1;
					add();
				})
			}
			this.EMPTY(commodity[0]['restaurant_id']).then(res => {
				console.log(res);
				setTimeout(() => {
					add();
				}, 1000);
			})
		},

		/**
		 * @param {type} 		路线规划方式参数：公交：bus 驾车：drive 步行：walk 骑行：bike
		 * @param {from} 		起点名称
		 * @param {fromcoord}	起点坐标(lat,lng) / CurrentLocation (使用定位点作为起点坐标)
		 * @param {to} 			终点名称
		 * @param {tocoord} 	终点坐标
		 * 
		 */
		MPAPI(latitude, longitude, name) {
			let url = "";
			if (plus.os.name == "Android") {
				let hasBaiduMap = plus.runtime.isApplicationExist({
					pname: 'com.baidu.BaiduMap',
					action: 'baidumap://'
				});
				let urlBaiduMap =
					`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`
				if (hasBaiduMap) {
					plus.runtime.openURL(urlBaiduMap);
				} else {
					plus.nativeUI.alert("未安装地图APP");
				}
			} else {
				plus.nativeUI.actionSheet({
						title: "选择地图应用",
						cancel: "取消",
						buttons: [{
							title: "Apple地图"
						}, {
							title: "百度地图"
						}]
					},

					function(e) {
						switch (e.index) {
							case 1:
								url =
									`http://maps.apple.com/?q=%e6%95%b0%e5%ad%97%e5%a4%a9%e5%a0%82&ll=${latitude},${longitude}&spn=0.008766,0.019441`;
								break;
							case 2:
								url =
									`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
								break;
							default:
								break;
						}
						if (url != "") {
							plus.runtime.openURL(url, function(e) {
								plus.nativeUI.alert("未安装地图APP");
							});
						}
					})
			}

		}
	},
	beforeDestroy() {
		clearTimeout(this['countDown']);
	},

};

export default restaurantmixins;
